/*
 * @lc app=leetcode.cn id=2981 lang=golang
 *
 * [2981] 找出出现至少三次的最长特殊子字符串 I
 */
package Solutions

import (
	"slices"
)

// @lc code=start
func maximumLength(s string) int {
	ans := 1
	mp := [26][]int{}
	current := s[0]
	l := 1
	for i := 1; i < len(s); i++ {
		if s[i] == current {
			l++
			continue
		}
		mp[current-'a'] = append(mp[current-'a'], l)
		l = 1
		current = s[i]
	}
	mp[current-'a'] = append(mp[current-'a'], l)
	ans = -1
	for i := range mp {
		if len(mp[i]) == 0 {
			continue
		}
		slices.Sort(mp[i])
		l := len(mp[i])
		if len(mp[i]) >= 3 && mp[i][len(mp[i])-3] > ans {
			ans = mp[i][len(mp[i])-3]
		}
		if mp[i][len(mp[i])-1]-2 > 0 && mp[i][len(mp[i])-1]-2 > ans {
			ans = mp[i][len(mp[i])-1] - 2
		}
		if l >= 2 && mp[i][l-1]-mp[i][l-2] == 1 && mp[i][l-2] > ans {
			ans = mp[i][l-2]
		}
		if l >= 2 && mp[i][l-1]-mp[i][l-2] == 0 && mp[i][l-1]-1 > 0 && mp[i][l-1]-1 > ans {
			ans = mp[i][l-1] - 1
		}
	}
	return ans
}

// @lc code=end
